package com.ysm.smfu.activity;

import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.ysm.smfu.MainActivity;
import com.ysm.smfu.R;
import com.ysm.smfu.bean.User;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.StoreInfo;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.welcome.SharedConfig;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import chatuidemo.DemoHelper;
import chatuidemo.db.DBManager;

/**
 * Created by Administrator on 2016/9/20.
 */
public class Registe_setpsdActivity extends BaseActivity {


    @BindView(R.id.register_setpsd_top_bar_title)
    TextView registerSetpsdTopBarTitle;
    @BindView(R.id.et_activity_register_password)
    EditText etActivityRegisterPassword;
    @BindView(R.id.et_activity_register_repassword)
    EditText etActivityRegisterRepassword;
    @BindView(R.id.btn_activity_setpsd_register_register)
    Button btnActivitySetpsdRegisterRegister;
    private String phoneNumber;
    private String codeString;
    private SharedPreferences sp;
    private ProgressDialog progressDialog;
    private User userInfo;
    private SharedPreferences currSP;

    @Override
    protected void initViews() {
        super.initViews();
        setContentView(R.layout.activity_register_setpsd);
        ButterKnife.bind(this);
        sp = new SharedConfig(UIUtils.getContext()).getCommoneSp();
        getIntentData();
    }

    /**
     * 获取Intent传递过来的数据
     */
    private void getIntentData() {
        phoneNumber = getIntent().getStringExtra(UIUtils.intentData);
        codeString = getIntent().getStringExtra(UIUtils.intentCode);

    }

    //首次输入的密码
    private String psd;
    //两次密码输入是否一致
    private boolean isSame;

    @Override
    protected void initListener() {
        super.initListener();
    }


    @OnClick(R.id.btn_activity_setpsd_register_register)
    public void onClick() {
        if (!checkPsd()) {
            return;
        }
        checkSame();
        if (isSame) {
            showDialg();
            setLoginPsd();
        }
    }

    /**
     * 设置登录密码
     * /userRegister
     * username : 用户名
     * pwd : 密码
     */
    private void setLoginPsd() {
        BaseProtocal.builder(false).setLoginPsd(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("设置登录密码" , response);
                String state = JsonUtil.getState(response);
                if (!TextUtils.equals(state, "1")) {
                    ToastUtils.showToast(JsonUtil.getMessage(response));
                    cancleDialog();
                    return;
                }
                // 如果设置成功，则跳转
                login(phoneNumber, psd);
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showToast(getResources().getString(R.string.netError));
            }
        }, psd, phoneNumber, codeString);
    }

    /**
     * 登录：同时登陆环信和后台
     *
     * @param numPhone
     * @param psd
     */
    private void login(final String numPhone, final String psd) {
        BaseProtocal.builder(false).login(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("登录信息" ,response);
                String state = JsonUtil.getState(response);
                if (!TextUtils.equals(state, "1")) {
                    ToastUtils.showToast(JsonUtil.getMessage(response));
                    cancleDialog();
                    return;
                }
                userInfo = JsonUtil.getUserInfo(response);
//                友盟统计用户Id
                MobclickAgent.onProfileSignIn(numPhone);
                loginHx(userInfo.user.hxId, userInfo.user.pwd);
            }

            @Override
            public void onFail(Exception e) {
                cancleDialog();
                ToastUtils.showToast("网络繁忙，请稍后重试");
            }
        }, numPhone, psd, false);
    }

    /**
     * 环信登录
     *
     * @param psd
     */
    private void loginHx(final String hxId, final String psd) {
        DBManager.getInstance().closeDB();
//        用户昵称为环信ID
        DemoHelper.getInstance().setCurrentUserName(hxId);

//        已经登陆过，不需再登陆
        if (EMClient.getInstance().isLoggedInBefore()) {
            EMClient.getInstance().logout(false, new EMCallBack() {
                @Override
                public void onSuccess() {
                    loginToHx(hxId, psd);
                }

                @Override
                public void onError(int i, String s) {

                }

                @Override
                public void onProgress(int i, String s) {

                }
            });
            return;
        }
        loginToHx(hxId, psd);
    }

    /**
     * 登录到环信
     *
     * @param hxId
     * @param psd
     */
    private void loginToHx(String hxId, String psd) {
        //环信登录
        EMClient.getInstance().login(hxId, psd, new EMCallBack() {
            @Override
            public void onSuccess() {
                saveInfoAndTo();
            }

            @Override
            public void onProgress(int progress, String status) {
            }

            @Override
            public void onError(final int code, final String message) {
                PrintUtil.printRespones("环信登录" , message);
                cancleDialog();
                Looper.prepare();
                showErrordialog(message);
                Looper.loop();
            }
        });
    }

    /**
     * 保存信息并且跳转
     */
    private void saveInfoAndTo() {
        //        将用户信息保存到数据库和xml文件中
        DBManager.getInstance().saveContact2(userInfo.user);
        sp.edit().putString(SpKey.NAME, phoneNumber).commit();
        currSP = new SharedConfig(UIUtils.getContext(), phoneNumber).getPrivateSp();
        StoreInfo.getInstance().storeBasicInfo(currSP, userInfo);

        // 取消进度条
        cancleDialog();
        UIUtils.startActivity(MainActivity.class);
        finish();
    }

    /**
     * 显示进度对话框
     */
    private void showDialg() {
        cancleDialog();
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在登录中...");
        progressDialog.show();
    }

    private void cancleDialog() {
        if (progressDialog != null && progressDialog.isShowing())
            progressDialog.dismiss();
    }

    private boolean checkPsd() {
        psd = etActivityRegisterPassword.getText().toString().trim();
        etActivityRegisterPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                etActivityRegisterRepassword.setText("");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        if (psd.length() < 6 || psd.length() > 20 || !psd.matches(SpKey.MIMAREGEX)) {
            showErrordialog("密码必须同时包含字母和数字，不得少于六位");
            return false;
        }
        return true;
    }

    /**
     * 显示错误对话框
     */
    private void showErrordialog(String msg) {
        AlertDialog dialog = new AlertDialog.Builder(this).setMessage(msg)
                .setNegativeButton("确定", null)
                .create();
        dialog.show();
    }

    /**
     * 检测两次输入是否一致
     */
    private void checkSame() {
        String repsd = etActivityRegisterRepassword.getText().toString().trim();
        if (TextUtils.isEmpty(psd) || TextUtils.isEmpty(repsd) || !TextUtils.equals(repsd, psd)) {
            isSame = false;
            showErrordialog("密码不能为空，且必须一致");
        } else {
            isSame = true;
        }
    }
}
